<?php

/**
 * 用户积分模型
 * File Name：MembersInfoModel.php
 * File Encoding：UTF-8
 * File New Time：2014-5-15 14:59:08
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class MembersInfoModel extends BaseModel {

    public function tableName() {
        return '{{members_info}}';
    }

    public function rules() {
        return array(
           // array('alipay,alipay_name', 'required'),
            array('sex, province,score,city,year,month,day,alipay,alipay_name,phone', 'safe'),
        );
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    /**
     * 增加积分，以后要加上版本控制，不然不够严谨
     * @param type $uid 用户ID
     * @param type $score 需要增加的积分
     * @param type $log 积分增加原因
     * @return boolean
     */
    public function plusScore($uid, $score, $log = '') {
        $data = $this->findByPk((int) $uid);
        if (empty($data)) {
            $this->addError('', '该用户不存在，无法增加积分！');
            return false;
        }
        $data->score = $data->score + (int) $score;
        if ($data->validate() && $data->save()) {
            //增加积分日志
            if (!empty($log)) {
                MembersActionModel::model()->addAction($uid, MembersActionModel::action_system, $log);
            }
            return true;
        }
        $this->addError('score', '积分增加失败！');
        return false;
    }

    /**
     * 积分扣除
     * @param type $uid 用户ID
     * @param type $score 需要扣除的积分数
     * @return boolean
     */
    public function deductionScore($uid, $score, $log = '') {
        $data = $this->findByPk((int) $uid);
        if (empty($data)) {
            $this->addError('score', '该用户积分为0，无法扣除积分！');
            return false;
        }
        if ($data->score - $score < 0) {
            $this->addError('score', '该用户积分不足，无法扣除积分！<a target="_blank" style="color:blue;" href="http://www.mamijie.com/article/12.html">点击了解如何获取更多的积分</a>');
            return false;
        }
        $data->score = $data->score - (int) $score;
        if ($data->validate() && $data->save()) {
            //增加积分日志
            if (!empty($log)) {
                MembersActionModel::model()->addAction($uid, MembersActionModel::action_system, $log);
            }
            return true;
        }
        $this->addError('score', '扣除积分失败！');
        return false;
    }

    /**
     * 获取会员扩展信息
     * @param type $uid 用户UID
     * @return boolean
     */
    public function getUserInfo($uid) {
        $userInfo = $this->findByPk($uid);
        if (empty($userInfo)) {
            return false;
        }
        return $userInfo->attributes;
    }

    /**
     * 判断手机号是号唯一
     * @return [type] [description]
     */
    public static function getByPhone($phone){
        return  MembersInfoModel::model()->find('phone = :phone', array('phone' => $phone));
    }

}
